/**
 * Created by leo on 5/27/16.
 */

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

var net = require('net');
var request = require('request');

app.use(bodyParser.json());

Genre = require('./models/genre');
Book = require('./models/book');
Device = require('./models/device');
Category = require('./models/category');
Room = require('./models/room');

// Connect to Mongoose
mongoose.connect('mongodb://localhost/bookstore');
var db = mongoose.connection;

app.get('/', function(req, res) {
    res.send('Please use /api/');
});


//******************* device
app.use('/api/devices', require('./routes/devices'));

//******************* Category
app.use('/api/categories', require('./routes/categories'));

//******************* room
app.use('/api/rooms', require('./routes/rooms'));


//******************* socket
var HOST = '0.0.0.0';
var PORT = 9999;

var clients = [];

net.createServer(function(sock) {
    // 获得一个Socket连接 - 该连接自动关联一个socket对象
    // 将除了127.0.0.1之外的加入列表
    if (sock.remoteAddress != '127.0.0.1') {
        console.log('\<Socket\> 设备 "' +
            sock.remoteAddress + ':' + sock.remotePort +
            '" 已连接到服务端'
        );
    }
    clients.push(sock);

    // 为这个socket实例添加一个"data"事件处理函数
    sock.on('data', function(data) {
        console.log('\<Socket\> Data [' + data + ']');
        // 回发数据，客户端将收到来自服务端的数据
        // TODO: 在此处理设备命令，设备->Socket->推送->App；APP->RestAPI->Socket->设备

        if (data == 'on') {
            // App请求过来的[on]，发到设备
            broadcast(new Buffer('~ZJNU00011\xAA', 'ascii'), sock);
            // 删除client
            clients.pop();
        } else if (data == 'off') {
            // App请求过来的[off]，发到设备
            broadcast(new Buffer('~ZJNU00010\xAA', 'ascii'), sock);
            // 删除client
            clients.pop();
        } else {
            // 此时是设备发送过来的
            console.log('收到设备的请求');
            var command = data.slice(9, 10) == '1' ? 'on' : 'off';
            var id = '11111111';
            // 请求Bmob推送
            var options = {
                url: 'http://127.0.0.1:3000/api/devices/' + id + '/' + command,
                method: 'GET',
            };
            request(options, function (err, response, body) {
                console.log('请求 [' + command + '] 成功转发');
            });
        }
    });

    sock.on('error', function (err) {
        // 处理设备Socket连接重置???
        //console.log(err);
    });

    // 为这个socket实例添加一个"close"事件处理函数
    sock.on('close', function(data) {
        if (sock.remoteAddress != '127.0.0.1') {
            console.log('\<Socket\> 设备 "' +
                sock.remoteAddress + ':' + sock.remotePort +
                '" 已断开'
            );
        }
    });

    function broadcast(message, sender) {
        clients.forEach(function (client) {
            // 可以发回给sender
            if (client === sender) {
                client.write('success')
            } else {
                client.write(message);
            }
        });
        // Log it to the server output too
        process.stdout.write(message)
    }
}).listen(PORT, HOST);



app.listen(3000);
console.log('Running on port 3000...');

